package com.shensi.adminCollect.controller.customer;

import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.domain.entity.SysDept;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.common.redis.service.RedisCache;
import com.shensi.adminCollect.common.exception.CustomException;
import com.shensi.adminCollect.common.utils.poi.ExcelUtil;
import com.shensi.adminCollect.domain.customer.CustomerCardSetting;
import com.shensi.adminCollect.domain.customer.CustomerElectronicCard;
import com.shensi.adminCollect.domain.customer.ElecSumInfo;
import com.shensi.adminCollect.enums.customer.ElectronCardType;
import com.shensi.adminCollect.service.customer.ICustomerCardSettingService;
import com.shensi.adminCollect.service.customer.ICustomerElectronicCardService;
import com.shensi.adminCollect.domain.system.SysEnterpriseUser;
import com.shensi.adminCollect.service.system.ISysDeptService;
import com.shensi.adminCollect.service.system.ISysEnterpriseUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * 客户电子会员卡充值优惠设置Controller
 *
 * @author qujia
 * @date 2021-04-06
 */
@RestController
@RequestMapping("/customer/cardsetting")
public class CustomerCardSettingController extends BaseController
{
    @Autowired
    private ICustomerCardSettingService customerCardSettingService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysEnterpriseUserService sysEnterpriseUserService;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ICustomerElectronicCardService customerElectronicCardService;

    /**
     * 查询客户电子会员卡充值优惠设置列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CustomerCardSetting customerCardSetting)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        customerCardSetting.setStationId(currentUser.getUser().getDeptId());
        startPage();
        List<CustomerCardSetting> settingList = customerCardSettingService.selectCustomerCardSettingList(customerCardSetting);
        return getDataTable(settingList);
    }

    /**
     * 查询客户电子会员卡充值优惠设置列表
     */
    @GetMapping("/listSetting")
    public AjaxResult listSetting(CustomerCardSetting customerCardSetting)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //设置油企id就是stationid信息
        customerCardSetting.setStationId(currentUser.getUser().getEnterpriseId());
        startPage();
        List<CustomerCardSetting> settingList = customerCardSettingService.selectCustomerCardSettingList(customerCardSetting);
        List<CustomerCardSetting> settings=new ArrayList<>();
        for(CustomerCardSetting customerCardSetting1:settingList){
           if(customerCardSetting1.getCardOilsType() !=null&&(!"".equals(customerCardSetting.getCardOilsType()))){
               List<String> oillist=new ArrayList<>();
               String [] oils=customerCardSetting1.getCardOilsType().split(",");
               for(String mm:oils){
                   oillist.add(mm);
               }
               customerCardSetting1.setCardOilsTypeList(oillist);
           }
            if(customerCardSetting1.getGasolineRule() !=null &&(!"".equals(customerCardSetting.getGasolineRule()))){
                List<String> Gasolist=new ArrayList<>();
                String [] gaso=customerCardSetting1.getGasolineRule().split(",");
                for(String mm:gaso){
                    Gasolist.add(mm);
                }
                customerCardSetting1.setGasolineRuleList(Gasolist);
            }
            if(customerCardSetting1.getDieselOilRule() !=null&&(!"".equals(customerCardSetting.getDieselOilRule()))){
                List<String> dieselist=new ArrayList<>();
                String [] diese=customerCardSetting1.getDieselOilRule().split(",");
                for(String mm:diese){
                    dieselist.add(mm);
                }
                customerCardSetting1.setDieselOilRuleList(dieselist);
            }
            if(customerCardSetting1.getLNGRule() !=null&&(!"".equals(customerCardSetting.getLNGRule()))){
                List<String> LNGlist=new ArrayList<>();
                String [] LNGs=customerCardSetting1.getLNGRule().split(",");
                for(String mm:LNGs){
                    LNGlist.add(mm);
                }
                customerCardSetting1.setLNGRuleList(LNGlist);
            }
            if(customerCardSetting1.getCNGRule() !=null&&(!"".equals(customerCardSetting.getCNGRule()))){
                List<String> CNGlist=new ArrayList<>();
                String [] CNGs=customerCardSetting1.getCNGRule().split(",");
                for(String mm:CNGs){
                    CNGlist.add(mm);
                }
                customerCardSetting1.setCNGRuleList(CNGlist);
            }
            if("3".equals(customerCardSetting1.getDiscountTimeType())){
                if(customerCardSetting1.getDiscountTime() !=null&&(!"".equals(customerCardSetting.getDiscountTime()))){
                    List<String> dislist=new ArrayList<>();
                    List<String> dislist1=new ArrayList<>();
                    String [] CNGs=customerCardSetting1.getDiscountTime().split(",");
                    for(String mm:CNGs){
                        dislist.add(mm);
                    }
                    customerCardSetting1.setCollectClickCalendar(dislist);
                    customerCardSetting1.setCollectClickDay(dislist1);
                }
            }else {
                if(customerCardSetting1.getDiscountTime() !=null &&(!"".equals(customerCardSetting.getDiscountTime()))){
                    List<String> dislist=new ArrayList<>();
                    List<String> dislist1=new ArrayList<>();
                    String [] CNGs=customerCardSetting1.getDiscountTime().split(",");
                    for(String mm:CNGs){
                        dislist.add(mm);
                    }
                    customerCardSetting1.setCollectClickDay(dislist);
                    customerCardSetting1.setCollectClickCalendar(dislist1);
                }
            }
            settings.add(customerCardSetting1);
        }
        CustomerCardSetting customerCardSetting1=new CustomerCardSetting();
         if(settings.size()>0){
             customerCardSetting1=settings.get(0);
         }else {
             customerCardSetting1.setCardEnabledFlag("0");
         }
        return AjaxResult.success(customerCardSetting1);
    }

    /**
     * 导出客户电子会员卡充值优惠设置列表
     */
    @GetMapping("/export")
    public AjaxResult export(CustomerCardSetting customerCardSetting)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();

        customerCardSetting.setStationId(currentUser.getUser().getDeptId());
        List<CustomerCardSetting> settingList = customerCardSettingService.selectCustomerCardSettingList(customerCardSetting);
        ExcelUtil<CustomerCardSetting> util = new ExcelUtil<CustomerCardSetting>(CustomerCardSetting.class);
        return util.exportExcel(settingList, "setting");
    }

    /**
     * 获取客户电子会员卡充值优惠设置详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(customerCardSettingService.selectCustomerCardSettingById(id));
    }

    /**
     * 获取电子卡的信息
     */
    @GetMapping(value = "/settingInfo/{id}")
    public AjaxResult settingInfo(@PathVariable("id") Long id)
    {
        CustomerCardSetting customerCardSetting=customerCardSettingService.selectCustomerCardSettingById(id);
        if(customerCardSetting.getCardOilsType() !=null&&!"".equals(customerCardSetting.getCardOilsType())){
            List<String> oillist=new ArrayList<>();
            String [] oils=customerCardSetting.getCardOilsType().split(",");
            for(String mm:oils){
                oillist.add(mm);
            }
            customerCardSetting.setCardOilsTypeList(oillist);
        }
        if(customerCardSetting.getGasolineRule() !=null&&!"".equals(customerCardSetting.getGasolineRule())){
            List<String> Gasolist=new ArrayList<>();
            String [] gaso=customerCardSetting.getGasolineRule().split(",");
            for(String mm:gaso){
                Gasolist.add(mm);
            }
            customerCardSetting.setGasolineRuleList(Gasolist);
        }
        if(customerCardSetting.getDieselOilRule() !=null&&!"".equals(customerCardSetting.getDieselOilRule())){
            List<String> dieselist=new ArrayList<>();
            String [] diese=customerCardSetting.getDieselOilRule().split(",");
            for(String mm:diese){
                dieselist.add(mm);
            }
            customerCardSetting.setDieselOilRuleList(dieselist);
        }
        if(customerCardSetting.getLNGRule() !=null&&!"".equals(customerCardSetting.getLNGRule())){
            List<String> LNGlist=new ArrayList<>();
            String [] LNGs=customerCardSetting.getLNGRule().split(",");
            for(String mm:LNGs){
                LNGlist.add(mm);
            }
            customerCardSetting.setLNGRuleList(LNGlist);
        }
        if(customerCardSetting.getCNGRule() !=null&&!"".equals(customerCardSetting.getCNGRule())){
            List<String> CNGlist=new ArrayList<>();
            String [] CNGs=customerCardSetting.getCNGRule().split(",");
            for(String mm:CNGs){
                CNGlist.add(mm);
            }
            customerCardSetting.setCNGRuleList(CNGlist);
        }
        return AjaxResult.success(customerCardSetting);
    }

    /**
     * 新增客户电子会员卡充值优惠设置
     */
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody CustomerCardSetting customerCardSetting)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        customerCardSetting.setStationId(currentUser.getUser().getDeptId());
        if(customerCardSetting!=null &&customerCardSetting.getCardEnabledFlag()!=null && !customerCardSetting.getCardEnabledFlag().equals("")){
            SysDept dept = new SysDept();
            dept.setDeptId(currentUser.getUser().getDeptId());
            dept.setIntegralFlag(customerCardSetting.getCardEnabledFlag());
            deptService.updateDeptInfo(dept);
        }
        return toAjax(customerCardSettingService.insertCustomerCardSetting(customerCardSetting));
    }

    /**
     * 新增客户电子会员卡充值优惠设置
     */
    @PostMapping(value = "/addSetting")
    @Transactional
    public AjaxResult addSetting(@RequestBody CustomerCardSetting customerCardSetting)
    {
        LoginUser current=SecurityUtils.getLoginUser();
        SysEnterpriseUser sysEnterpriseUser=new SysEnterpriseUser();
        sysEnterpriseUser.setEnterpriseId(current.getUser().getEnterpriseId());
        sysEnterpriseUser.setCardFlag(customerCardSetting.getCardEnabledFlag());
        sysEnterpriseUser.setCardUseRangeFlag(customerCardSetting.getCardUseRangeFlag());
        sysEnterpriseUserService.updateSysEnterpriseUser(sysEnterpriseUser);
        //设置油企id就是stationid信息
        customerCardSetting.setEnterpriseId(current.getUser().getEnterpriseId());
        customerCardSetting.setStationId(current.getUser().getEnterpriseId());
        String oill="";
        String gasoline="";
        String diesel="";
        String LNGRule="";
        String CNGRule="";
        String day="";


        //LoginUser currentUser = SecurityUtils.getLoginUser();
        if(customerCardSetting.getCardOilsTypeList()!=null&&customerCardSetting.getCardOilsTypeList().size()>0){
            for(String mm:customerCardSetting.getCardOilsTypeList()){
                if("".equals(oill)){
                    oill+=mm;
                }else {
                    oill+=","+mm;
                }
            }
            customerCardSetting.setCardOilsType(oill);
        }
        if(customerCardSetting.getGasolineRuleList()!=null&&customerCardSetting.getGasolineRuleList().size()>0){
            for(String mm:customerCardSetting.getGasolineRuleList()){
                if("".equals(gasoline)){
                    gasoline+=mm;
                }else {
                    gasoline+=","+mm;
                }
            }
            customerCardSetting.setGasolineRule(gasoline);
        }
        if(customerCardSetting.getDieselOilRuleList()!=null&&customerCardSetting.getDieselOilRuleList().size()>0){
            for(String mm:customerCardSetting.getDieselOilRuleList()){
                if("".equals(diesel)){
                    diesel+=mm;
                }else {
                    diesel+=","+mm;
                }
            }
            customerCardSetting.setDieselOilRule(diesel);
        }

        if(customerCardSetting.getLNGRuleList()!=null&&customerCardSetting.getLNGRuleList().size()>0){
            for(String mm:customerCardSetting.getLNGRuleList()){
                if("".equals(LNGRule)){
                    LNGRule+=mm;
                }else {
                    LNGRule+=","+mm;
                }
            }
            customerCardSetting.setDieselOilRule(LNGRule);
        }
        if(customerCardSetting.getCNGRuleList()!=null&&customerCardSetting.getCNGRuleList().size()>0){
            for(String mm:customerCardSetting.getCNGRuleList()){
                if("".equals(CNGRule)){
                    CNGRule+=mm;
                }else {
                    CNGRule+=","+mm;
                }
            }
            customerCardSetting.setCNGRule(CNGRule);
        }
        if(customerCardSetting.getCollectClickDay()!=null&&customerCardSetting.getCollectClickDay().size()>0){
            for(String mm:customerCardSetting.getCollectClickDay()){
                if("".equals(day)){
                    day+=mm;
                }else {
                    day+=","+mm;
                }
            }
            customerCardSetting.setDiscountTime(day);
        }
        if(customerCardSetting.getCollectClickCalendar()!=null&&customerCardSetting.getCollectClickCalendar().size()>0){
            for(String mm:customerCardSetting.getCollectClickCalendar()){
                if("".equals(day)){
                    day+=mm;
                }else {
                    day+=","+mm;
                }
            }
            customerCardSetting.setDiscountTime(day);
        }


        return toAjax(customerCardSettingService.insertCustomerCardSetting(customerCardSetting));
    }

    /**
     * 修改客户电子会员卡充值优惠设置
     */
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody CustomerCardSetting customerCardSetting)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        customerCardSetting.setStationId(currentUser.getUser().getDeptId());
        int i =0;
        if(customerCardSetting!=null&&customerCardSetting.getCardEnabledFlag()!=null && !customerCardSetting.getCardEnabledFlag().equals("")){
            if(customerCardSetting.getCardEnabledFlag().equals("1")){
                SysDept dept =new SysDept();
                dept.setDeptId(currentUser.getUser().getDeptId());
                dept.setCardEnabledFlag(customerCardSetting.getCardEnabledFlag());
                i= deptService.updateDeptInfo(dept);
                if(i==1) {
                    i = customerCardSettingService.updateCustomerCardSetting(customerCardSetting);
                }
            }else if(customerCardSetting.getCardEnabledFlag().equals("0")){
                SysDept dept =new SysDept();
                dept.setDeptId(currentUser.getUser().getDeptId());
                dept.setCardEnabledFlag(customerCardSetting.getCardEnabledFlag());
                i= deptService.updateDeptInfo(dept);
            }
        }
        return toAjax(i);
    }
    /**
     * 修改客户电子会员卡充值优惠设置
     */
    @PostMapping(value = "/editSetting")
    @Transactional
    public AjaxResult editSetting(@RequestBody CustomerCardSetting customerCardSetting)
    {

        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysEnterpriseUser sysEnterpriseUser=new SysEnterpriseUser();
        sysEnterpriseUser.setEnterpriseId(currentUser.getUser().getEnterpriseId());
        sysEnterpriseUser.setCardFlag(customerCardSetting.getCardEnabledFlag());
        sysEnterpriseUser.setCardUseRangeFlag(customerCardSetting.getCardUseRangeFlag());

        checkSetting(customerCardSetting);

        redisCache.deleteObject("EnterpriseServiceImpl_selectEnterpriseInfo::" + "e_" +customerCardSetting.getEnterpriseId() );
        sysEnterpriseUserService.updateSysEnterpriseUser(sysEnterpriseUser);
        redisCache.deleteObject("EnterpriseServiceImpl_selectEnterpriseInfo::" + "e_" +customerCardSetting.getEnterpriseId() );
       int i=0;
        String oill="";
        String gasoline="";
        String diesel="";
        String LNGRule="";
        String CNGRule="";
        String day="";
        if(customerCardSetting.getCardOilsTypeList()!=null&&customerCardSetting.getCardOilsTypeList().size()>0){
            for(String mm:customerCardSetting.getCardOilsTypeList()){
                if("".equals(oill)){
                    oill+=mm;
                }else {
                    oill+=","+mm;
                }
            }
            customerCardSetting.setCardOilsType(oill);
        }
        if(customerCardSetting.getGasolineRuleList()!=null&&customerCardSetting.getGasolineRuleList().size()>0){
            for(String mm:customerCardSetting.getGasolineRuleList()){
                if("".equals(gasoline)){
                    gasoline+=mm;
                }else {
                    gasoline+=","+mm;
                }
            }
            customerCardSetting.setGasolineRule(gasoline);
        }else {
            customerCardSetting.setGasolineRule("");
        }
        if(customerCardSetting.getDieselOilRuleList()!=null&&customerCardSetting.getDieselOilRuleList().size()>0){
            for(String mm:customerCardSetting.getDieselOilRuleList()){
                if("".equals(diesel)){
                    diesel+=mm;
                }else {
                    diesel+=","+mm;
                }
            }
            customerCardSetting.setDieselOilRule(diesel);
        }else {
            customerCardSetting.setDieselOilRule("");
        }

        if(customerCardSetting.getLNGRuleList()!=null&&customerCardSetting.getLNGRuleList().size()>0){
            for(String mm:customerCardSetting.getLNGRuleList()){
                if("".equals(LNGRule)){
                    LNGRule+=mm;
                }else {
                    LNGRule+=","+mm;
                }
            }
            customerCardSetting.setDieselOilRule(LNGRule);
        }else {
            customerCardSetting.setDieselOilRule("");
        }
        if(customerCardSetting.getCNGRuleList()!=null&&customerCardSetting.getCNGRuleList().size()>0){
            for(String mm:customerCardSetting.getCNGRuleList()){
                if("".equals(CNGRule)){
                    CNGRule+=mm;
                }else {
                    CNGRule+=","+mm;
                }
            }
            customerCardSetting.setCNGRule(CNGRule);
        }else {
            customerCardSetting.setCNGRule("");
        }
        if(customerCardSetting.getCollectClickDay()!=null&&customerCardSetting.getCollectClickDay().size()>0){
            for(String mm:customerCardSetting.getCollectClickDay()){
                if("".equals(day)){
                    day+=mm;
                }else {
                    day+=","+mm;
                }
            }
            customerCardSetting.setDiscountTime(day);
        }else {
            if(!"3".equals(customerCardSetting.getDiscountTimeType())){
                customerCardSetting.setDiscountTime("");
            }

        }
        if(customerCardSetting.getCollectClickCalendar()!=null&&customerCardSetting.getCollectClickCalendar().size()>0){
            for(String mm:customerCardSetting.getCollectClickCalendar()){
                if("".equals(day)){
                    day+=mm;
                }else {
                    day+=","+mm;
                }
            }
            customerCardSetting.setDiscountTime(day);
        }else {
            if("3".equals(customerCardSetting.getDiscountTimeType())){
                customerCardSetting.setDiscountTime("");
            }
        }

        i=customerCardSettingService.updateCustomerCardSetting(customerCardSetting);
        return toAjax(i);
    }

    /**
     * 删除客户电子会员卡充值优惠设置
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(customerCardSettingService.deleteCustomerCardSettingByIds(ids));
    }

    /**
     * 查询油站电子卡规则设置
     * @param customerCardSetting
     * @return
     */
    @GetMapping(value = "/selectCustomerCardSetting")
    @Transactional
    public AjaxResult selectCustomerCardSetting(CustomerCardSetting customerCardSetting)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        customerCardSetting.setStationId(currentUser.getUser().getDeptId());
        return AjaxResult.success(customerCardSettingService.selectCustomerCardSetting(customerCardSetting));
    }

    /**
     * 查询电子卡是否启用
     */
    @GetMapping(value = "/selectCardOpen")
    public AjaxResult selectCardOpen(CustomerCardSetting customerCardSetting)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //查询电子卡是否开启
        SysDept dept  = deptService.selectDeptById(currentUser.getUser().getDeptId());
        CustomerCardSetting cardSetting =new  CustomerCardSetting();
        if(dept!=null &&dept.getCardEnabledFlag()!=null&& dept.getCardEnabledFlag().equals("1")){
            //查询开启的电子卡
            CustomerCardSetting setting =new CustomerCardSetting();
            setting.setStationId(dept.getDeptId());
            cardSetting=  customerCardSettingService.selectCustomerCardSetting(setting);
        }else{
            cardSetting.setCardOilsType("");
        }
        return AjaxResult.success(cardSetting);
    }

    private void checkSetting(CustomerCardSetting newSetting){
        CustomerCardSetting old = customerCardSettingService.selectCustomerCardSettingById(newSetting.getId());
        if (StringUtils.isNotBlank(newSetting.getCardUseRangeFlag())) {
            if (StringUtils.isNotBlank(old.getCardUseRangeFlag())
                    && !StringUtils.equals(old.getCardUseRangeFlag(),newSetting.getCardUseRangeFlag())) {
                throw new CustomException("暂时不允许切换权限，请联系管理员！");
            }
        }
        boolean checkBalance = StringUtils.equals("0", newSetting.getCardEnabledFlag()) && StringUtils.equals("1",old.getCardEnabledFlag());
        List<ElecSumInfo> balanceSum = null;
        if (checkBalance) {
            CustomerElectronicCard formCard = new CustomerElectronicCard();
            formCard.setEnterpriseId(newSetting.getEnterpriseId());
            balanceSum = customerElectronicCardService.getBalanceSum(formCard, StringUtils.equals("1", old.getCardUseRangeFlag()));
            boolean b = balanceSum.stream().anyMatch(e -> e.getAmt().compareTo(BigDecimal.ZERO) > 0);
            if (b) {
                throw new CustomException("用户电子卡余额不为零，无法关闭！");
            }
        }
        if (StringUtils.isBlank(old.getCardOilsType())) {
            return;
        }
        String[] split = old.getCardOilsType().split(",");
        HashSet<String> oldTypes = new HashSet<>(Arrays.asList(split));
        if (oldTypes.isEmpty()) {
            return;
        }
        List<String> newTypes = newSetting.getCardOilsTypeList();
        for (String value : newTypes) {
            oldTypes.remove(value);
        }
        if (oldTypes.isEmpty()) {
            return;
        }
        if (balanceSum == null) {
            CustomerElectronicCard formCard = new CustomerElectronicCard();
            formCard.setEnterpriseId(newSetting.getEnterpriseId());
            balanceSum = customerElectronicCardService.getBalanceSum(formCard, StringUtils.equals("1", old.getCardUseRangeFlag()));
        }
        for (String s : oldTypes) {
            Optional<ElecSumInfo> find = balanceSum.stream().filter(e -> e.getType().equals(s)).findFirst();
            if (find.isPresent()) {
                ElecSumInfo info = find.get();
                if (info.getAmt().compareTo(BigDecimal.ZERO)>0) {
                    throw new CustomException("用户"+ ElectronCardType.getByKey(info.getType()).getName() +"卡余额不为零，无法关闭！");
                }
            }
        }

    }

}
